<?php

namespace app\data\service;

use think\admin\Service;

/**
 * 债权服务
 * Class PropertyService
 * @package app\data\service
 */
class PropertyService extends Service
{


    protected $orderInfo;

    protected $propertyInfo;

    /**
     * @param int $id
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo($id = 0){
        return $this->app->db->name('ShopProperty')->where('id', $id)->find();
    }

    /**
     * @param array $filter
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderProperty($filter = []){

        if (isset($filter['order_id'])){
            $where[] = ['sop.order_id','=', $filter['order_id']];
        }

        if (isset($filter['property_id'])){
            $where[] = ['sop.property_id','=', $filter['property_id']];
        }


        $where[] = ['sop.status', '=', 1];

        $list = $this->app->db->name('shop_order_property')->alias('sop')
            ->leftJoin('shop_order so', 'sop.order_id=so.id')
            ->leftJoin('shop_property sp', 'sop.property_id = sp.id')
            ->where($where)
            ->field('sop.*,so.end_at,so.name as user_name,so.money as order_money,so.contract_no,so.customer_no,sp.name as property_name, sp.cost as property_cost, sp.match_cost as property_match_cost')
            ->select()
            ->toArray();

        return $list;
    }

    public function getPropertyList(){
        return $this->app->db->name('ShopProperty')->where(['status' => 1])->order('sort desc, id desc')->select();
    }

    public function cancelProperty($relation_id){

        $relationInfo = $this->app->db->name('shop_order_property')->where('id', $relation_id)->find();

        $this->app->db->name('shop_order_property')->where('id', $relation_id)->delete();

        $this->app->db->name('shopProperty')->where(['id' => $relationInfo['property_id']])->dec('match_cost', $relationInfo['match_cost'])->update();

        $this->historyProperty(2, $relationInfo['order_id'], $relationInfo['property_id'],[], $relationInfo['match_cost']);

        return true;
    }

    public function cancelAllByOrderId($orderId){

        $all = $this->app->db->name('shop_order_property')->where('order_id', $orderId)->select();

        foreach ($all as $item){
           $this->cancelProperty($item['id']);
        }

        return true;
    }

    public function cancelAllByPropertyId($property_id){
        $all = $this->app->db->name('shop_order_property')->where('property_id', $property_id)->select();

        foreach ($all as $item){
            $this->cancelProperty($item['id']);
        }

        return true;
    }

    public function saveProperty($order_id, $property_id, $match_cost){
        $propertyInfo = $this->propertyInfo = $this->getInfo($property_id);

        $o_info = $this->orderInfo = OrderService::instance()->getInfo($order_id);

        if (($propertyInfo['cost'] - $propertyInfo['match_cost']) < $match_cost){
            return -1;
        }
        $this->app->db->startTrans();

        $countEx = $this->app->db->name('shop_order_property')->where([
            'order_id' => $order_id,
            'property_id' => $property_id,
            'status' => 1
        ])->count();

        if ($countEx > 0){
            //当前资产已匹配，如需重新匹配请删除后再试
            return -2;
        }

        $sumEx = $this->app->db->name('shop_order_property')->where([
            'order_id' => $order_id,
            'status'   => 1
        ])->sum('match_cost');

        if (($sumEx + $match_cost) > $o_info['money']){
            //超出当前投资的金额
            return -3;
        }

        try {
            $res = $this->app->db->name('shop_order_property')->insert([
                'order_id'      => $order_id,
                'property_id'   => $property_id,
                'match_cost'    => $match_cost
            ]);

            $this->app->db->name('shopProperty')->where(['id' => $property_id])->inc('match_cost', $match_cost)->update();

            $this->historyProperty(1, $order_id, $property_id,[], $match_cost);

            $this->app->db->commit();

            return 1;

        }catch (\Exception $exception){
            $this->app->db->rollback();
            return false;
        }
    }


    public function historyProperty($type = 1, $order_id = 0,$property_id = 0, $userinfo = [], $matchCost = 0.00){

        $p_info = $this->propertyInfo ?? $this->getInfo($property_id);
        $o_info = $this->orderInfo ?? OrderService::instance()->getInfo($order_id);
        $g_info = GoodsService::instance()->getInfo($o_info['goods_id']);

        return $this->app->db->name('shop_property_history')->insert([
            'type' => $type,
            'user_name' => isset($userinfo['user_name']) ? $userinfo['user_name'] : $o_info['name'],
            'user_phone' => isset($userinfo['user_phone']) ? $userinfo['user_phone'] : $o_info['phone'],
            'user_info' => json_encode($userinfo),
            'goods_id' => $o_info['goods_id'],
            'goods_info' => json_encode($g_info),
            'order_id' => $order_id,
            'order_info' => json_encode($o_info),
            'property_id' => $property_id,
            'property_name' => $p_info['name'],
            'property_info' => json_encode($p_info),
            'staff_id' => cookie('staff.id'),
            'match_cost' => $matchCost
        ]);

    }

}